import { Button, ButtonGroup, Skeleton, styled } from '@mui/material'
import { useContext, useState } from 'react'
import { AppContext } from '../../store/storeProvider'

type TSorting = {
	sortBy: string
	selectedSortBy: string
}

const SORTING = [
	{ name: 'Популярные', sortBy: 'popular' },
	{ name: 'Новинки', sortBy: 'new' },
	{ name: 'Сначала дешёвые', sortBy: 'cheap' },
	{ name: 'Сначала дорогие', sortBy: 'expensive' },
	{ name: 'По рейтингу', sortBy: 'rating' },
	{ name: 'По скидке', sortBy: 'discount' },
]

const StyledContainer = styled('div')(() => ({
	display: 'flex',
	flexDirection: 'row',
	justifyContent: 'space-between',
	marginTop: '20px',
	width: '992px',
	height: '34px',
	padding: '12px, 16px, 12px, 16px',
	borderRadius: '12px',
	gap: '16px',
	boxShadow: '0px 8px 16px 0px #60617029',
}))

const StyledButton = styled(Button, {
	shouldForwardProp: (props) =>
		props !== 'sortBy' && props !== 'selectedSortBy',
})<Pick<TSorting, 'sortBy' | 'selectedSortBy'>>(
	({ sortBy, selectedSortBy }) => ({
		textTransform: 'none',
		color: sortBy === selectedSortBy ? '#1A1A1A' : '#7B8E98',
		fontFamily: 'Nunito',
		fontSize: '14px',
		border: '0',
	})
)

const Sorting = () => {
	const { state } = useContext(AppContext)
	const [selectedSortBy, setSortBy] = useState('')
	const handleClick = (sortBy: string) => {
		setSortBy(sortBy)
	}

	return (
		<StyledContainer>
			{state.pending ? (
				<Skeleton variant='rounded' width={992} height={34} />
			) : (
				<>
					<ButtonGroup>
						{SORTING.map(({ name, sortBy }) => (
							<StyledButton
								key={sortBy}
								sortBy={sortBy}
								selectedSortBy={selectedSortBy}
								onClick={() => handleClick(sortBy)}
							>
								{name}
							</StyledButton>
						))}
					</ButtonGroup>
				</>
			)}
		</StyledContainer>
	)
}

export default Sorting
